package com.panfeng.xcloud.boss.provider.member.security.password;

import com.panfeng.xcloud.boss.provider.member.security.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 *
 * 密码验证配置
 *
 * @author xiaobo
 * @version 1.0
 * @since 2019-08-12
 */
@Component
public class PwdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private PwdAuthenticationFailureHandler pwdAuthenticationFailureHandler;

	@Autowired
	private PwdAuthenticationSuccessHandler pwdAuthenticationSuccessHandler;

	@Override
	public void configure(HttpSecurity http) {
		PwdAuthenticationFilter pwdAuthenticationFilter = new PwdAuthenticationFilter();

		pwdAuthenticationFilter.setAccountNumberParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_ACCOUNTNUMBER);
		pwdAuthenticationFilter.setPasswordParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_PASSWORD);
		pwdAuthenticationFilter.setClientIdParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_CLIENTID);
		pwdAuthenticationFilter.setClientSecretParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_CLIENTSECRET);
		pwdAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		pwdAuthenticationFilter.setAuthenticationSuccessHandler(pwdAuthenticationSuccessHandler);
		pwdAuthenticationFilter.setAuthenticationFailureHandler(pwdAuthenticationFailureHandler);

		PwdAuthenticationProvider pwdAuthenticationProvider = new PwdAuthenticationProvider();

		pwdAuthenticationProvider.setUserDetailsService(userDetailsService);

		http.authenticationProvider(pwdAuthenticationProvider)
				.addFilterAfter(pwdAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
	}

}
